<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .timeBox {
      margin: 100px auto;
      width: 500px;
      height: 80px;
      background: yellow;
    }

    .timeBox img {
      margin-right: 2px;
      float: left;
      display: block;
      height: 60px;
      width: 40px;
      border: 1px solid #ccc;
    }

    .timeBox span {
      margin-top: 20px;
      float: left;
      font-size: 20px;
      color: red;
    }
  </style>
</head>

<body>

  <div class="timeBox">
    <img src="./img/0.png" alt="">
    <img src="./img/0.png" alt="">
    <span>时</span>
    <img src="./img/0.png" alt="">
    <img src="./img/0.png" alt="">
    <span>分</span>
    <img src="./img/0.png" alt="">
    <img src="./img/0.png" alt="">
    <span>秒</span>

  </div>
  <script>
    // 数码时钟
    // -   根据定时器动态改变img 的src的路径    -   img.src = ''

    render(); //先调用，防止刷新出现空白！
    setInterval(function () {
      render()
    }, 1000)

    //渲染的函数
    function render() {
      let imgList = document.querySelectorAll(".timeBox  img")
      let now = new Date() //01：先获取到当前的时间
      let res = formatTime(now) //02：拿到小时和分钟和秒

      let str = res.split(":").join(""); // 03:204642字符串
      for (var i = 0; i < str.length; i++) {
        // console.log(str[i]); //拿到每一个字符串的元素 每一个数组元素渲染到页面（以img的形式）
        // console.log(imgList);
        imgList[i].src = `./img/${str[i]}.png`;
      }
    }

    //格式化函数
    function formatTime(now) {
      let h = now.getHours();
      h = h < 10 ? "0" + h : h
      let m = now.getMinutes();
      m = m < 10 ? "0" + m : m
      let s = now.getSeconds();
      s = s < 10 ? "0" + s : s
      return h + ":" + m + ":" + s
    }
  </script>
</body>

</html>